import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes,allAsyncRoute ,anyRoute } from "@/router/routes";
import { reqLogin, reqUserInfo, reqUserLogOut } from "@/api/acl";
import type { loginResponseData, userResponseData } from "@/api/acl/model";
import router from "@/router";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

//定义一个函数过滤出需要用户动态注册的异步路由
const findUserAsyncRoutes = (allAsyncRoute:any,routes:any) => {
  return allAsyncRoute.filter((item:any)=>{
    if(routes.includes(item.name)){
      if(item.children && item.children.length){
        item.children = findUserAsyncRoutes(item.children,routes)
      }
      return true
    }
  })
}

export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [],
    buttons:[]//按钮权限的存储
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result: loginResponseData = await reqLogin({ username, password });
        this.token = result.token;
        setToken(result.token);
        return "ok";
      } catch (e: any) {
        return Promise.reject(new Error(e.message));
      }
    },

    async getInfo() {
      try {
        let result:userResponseData = await reqUserInfo();
        this.name = "豪哥";
        this.avatar = result.avatar;
        
        //响应回来的按钮权限
        this.buttons = result.buttons;
        //响应回来的路由菜单权限
        let userAsyncRoute = findUserAsyncRoutes(allAsyncRoute,result.routes)
        //菜单的展示路由，仅仅是展示 还要进行路由表注册
        this.menuRoutes = [...userAsyncRoute,...staticRoutes];
        //获取异步路由和任意路由
        let allRouteAsyncAndAny = [...userAsyncRoute,anyRoute]
        //进行路由表注册
        allRouteAsyncAndAny.forEach(item=>{
          router.addRoute(item)
        })
        return "ok";
      } catch (e: any) {
        return Promise.reject(new Error(e.message));
      }
    },

    async reset() {
      try {
        //通知服务器:当前token退出登录，不需要了！！
        await reqUserLogOut();
        // 删除local中保存的token
        removeToken();
        // 提交重置用户信息的mutation
        this.token = "";
        this.name = "";
        this.avatar = "";
        //获取所有的路由
        let allRoute = router.getRoutes()
        //退出登录之前删除所有的路由
        allRoute.forEach((item:any)=>{
          router.removeRoute(item)
        })
        //保证常量路由的有:常量路由还需要存在
        staticRoutes.forEach(item=>{
          router.addRoute(item);
       })


        return "ok";
      } catch (e: any) {
        return Promise.reject(new Error(e.message));
      }
    },
  },
});
